package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import cn.qqtheme.framework.picker.OptionPicker
import cn.qqtheme.framework.widget.WheelView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.FeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.LoftMemberResponse
import com.gexiaobao.pigeon.app.model.bean.MapLocationBean
import com.gexiaobao.pigeon.app.model.param.AddDrippingParam
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.ActivityDeliveringThePigeonsBinding
import com.gexiaobao.pigeon.ui.activity.ActivityMapLocation
import com.gexiaobao.pigeon.ui.adapter.DeliveringPigeonAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogAddPigeon
import com.gexiaobao.pigeon.ui.dialog.RxDialogBackHint
import com.gexiaobao.pigeon.ui.dialog.RxMemberListDialog
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.finish
import me.hgj.jetpackmvvm.util.startActivity
import me.hgj.jetpackmvvm.util.startActivityForResult


/**
 * @Author      : hxw
 * @Date        : 2024/6/15 13:54
 * @Describe    : 我要交鸽
 */
class ActivityDeliveringThePigeons : BaseActivity<OrgDetailViewModel, ActivityDeliveringThePigeonsBinding>() {

    private val mAdapter: DeliveringPigeonAdapter by lazy { DeliveringPigeonAdapter(arrayListOf()) }
    private var mPositionColor = 0//记录上次选中位置(羽色)
    private var colorId = 0
    private lateinit var dialog: RxDialogAddPigeon
    private var mOrgId = 0
    private var mRaceId = 0
    private var mMemberId = 0
    private var mLatitude: Double = 0.0
    private var mLongitude: Double = 0.0
    private var loftMemberResult: ArrayList<LoftMemberResponse.ListData> = arrayListOf()
    private var mList: ArrayList<AddDrippingParam.PigeonInfoBean> = arrayListOf()
    private var isClickAddress: Boolean = false
    private var isClickAddressName: Boolean = false
    private var isClickName: Boolean = false
    private var isClickMobile: Boolean = false
    private lateinit var bean: MapLocationBean
    private var mProCityArea = ""
    private var addressResult = ""
    private var kvName = ""
    private var kvMobile = ""

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "我要交鸽"
        mDatabind.includeBar.tvRightMenu.isVisible = true
        mDatabind.includeBar.tvRightMenu.text = "订单"

        mOrgId = intent.getIntExtra("orgId", 0)
        mRaceId = intent.getIntExtra("raceId", 0)

        initAdapter()

        /** 回显adapter数据 */
        val result = CacheUtil.getDrippingPigeonList()
        if ("null" != result && result.isNotEmpty()) {
            mList = Gson().fromJson(result, object : TypeToken<ArrayList<AddDrippingParam.PigeonInfoBean>>() {}.type)
            mAdapter.setList(mList)
        }
        /** 回显基础信息数据 */
        val bean = CacheUtil.getMapLocationBean()
        if (bean != null) {
//            mDatabind.tvDrippingAddress.text = bean.address
//            mDatabind.tvAddressName.text = bean.name
            mLatitude = bean.latitude
            mLongitude = bean.longitude
        }
        kvName = KvUtils.decodeString("drippingName")
        mDatabind.etContactName.setText(kvName)
        kvMobile = KvUtils.decodeString("drippingMobile")
        mDatabind.etContactMobile.setText(kvMobile)
        val address = KvUtils.decodeString("drippingAddress")
        val addressName = KvUtils.decodeString("drippingAddressName")
        addressResult = (addressName + "\n" + address).trim()
        mDatabind.tvDrippingAddress.text = addressResult
//        mDatabind.tvAddressName.text = addressName

    }

    override fun onBackPressed() {
        backSaveInfo()
        return
    }

    private fun backSaveInfo() {
//        val name = KvUtils.decodeString("drippingName")
//        val mobile = KvUtils.decodeString("drippingMobile")
//        val address = KvUtils.decodeString("drippingAddress")
//        val addressName = KvUtils.decodeString("drippingAddressName")
        isClickName = kvName != mDatabind.etContactName.text.toString().trim()
        isClickMobile = kvMobile != mDatabind.etContactMobile.text.toString().trim()
        isClickAddress = addressResult != mDatabind.tvDrippingAddress.text.toString().trim()
//        isClickAddressName = addressName != mDatabind.tvAddressName.text.toString().trim()
        CacheUtil.setDrippingPigeonList(mList)
        if (!isClickAddress && !isClickName && !isClickMobile) {//都是false 说明内容没改动
            finish()
        } else {
            showBackDialog(isClickName, isClickMobile, isClickAddress)
        }
    }


    private fun showBackDialog(isClickName: Boolean, isClickMobile: Boolean, isClickAddress: Boolean) {
        val dialog = RxDialogBackHint(this)
        dialog.setSureViewText("保存并返回")
        dialog.setCancelViewText("返回")
        dialog.setTitleText("当前页面信息未保存\n\n是否确认离开?")
        dialog.setCommitListener {
            if (isClickName)
                KvUtils.encode("drippingName", mDatabind.etContactName.text.toString().trim())
            if (isClickMobile)
                KvUtils.encode("drippingMobile", mDatabind.etContactMobile.text.toString().trim())
            if (isClickAddress) {
                KvUtils.encode("drippingAddress", mDatabind.tvDrippingAddress.text.toString().trim())
                if (::bean.isInitialized) CacheUtil.setMapLocationBean(bean)
            }
//            KvUtils.encode("drippingAddressName", mDatabind.tvAddressName.text.toString().trim())
            dialog.dismiss()
            finish()
        }
        dialog.setCancelListener {
            if (isClickName) KvUtils.encode("drippingName", "")
            if (isClickMobile) KvUtils.encode("drippingMobile", "")
            if (isClickAddress) KvUtils.encode("drippingAddress", "")
//            if (isClickAddressName) KvUtils.encode("drippingAddressName", "")
            dialog.dismiss()
            finish()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun initAdapter() {
        mDatabind.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter)
        /** 添加动画 */
        mDatabind.swipeRecyclerView.itemAnimator = DefaultItemAnimator()

        mAdapter.addChildClickViewIds(R.id.ivProhibitPigoen)
        mAdapter.setOnItemChildClickListener { _, _, position ->
            mAdapter.removeAt(position)
            /** 通知适配器 */
            mAdapter.notifyItemRemoved(position)
            if (mList.size != 0) mList.removeAt(position)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.llAddDidiPigeon,
            mDatabind.tvSubmitOrder,
            mDatabind.llMapLocation,
            mDatabind.includeBar.tvRightMenu
        ) { it ->
            when (it) {
                mDatabind.includeBar.tvRightMenu -> {
                    startActivity<ActivityDrippingPigeonOrder>()
                }

                mDatabind.llMapLocation -> {
                    startActivityForResult<ActivityMapLocation> {
                        if (it != null) {
                            val mName = it.getStringExtra("name").toString()
                            val mAddress = it.getStringExtra("address").toString()
                            mDatabind.tvDrippingAddress.text = (mName + "\n" + mAddress).trim()
//                            mDatabind.tvAddressName.text = mName
                            mLatitude = it.getDoubleExtra("latitude", 0.0)
                            mLongitude = it.getDoubleExtra("longitude", 0.0)
                            mProCityArea = it.getStringExtra("proCityArea").toString()
                            bean = MapLocationBean(mName, mAddress, mLatitude, mLongitude)
                        }
                    }
                }

                mDatabind.tvSubmitOrder -> {
                    submitOrder()
                }

                mDatabind.llAddDidiPigeon -> {
                    showDialogAddPigeon()
                }

                mDatabind.includeBar.ivBack -> {
                    backSaveInfo()
                }
            }
        }
    }

    private fun submitOrder() {
        val mobileNumber = mDatabind.etContactMobile.text.toString().trim()
        val name = mDatabind.etContactName.text.toString().trim()
        val address = mDatabind.tvDrippingAddress.text.toString().trim()
        when {
            mList.isEmpty() -> RxToast.warning("请先添加赛鸽")
            address.isEmpty() -> RxToast.warning("请选择联系地址")
            name.isEmpty() -> RxToast.warning("填写联系人姓名")
            mobileNumber.isEmpty() -> RxToast.warning("请填写联系人电话")
            mobileNumber.isNotEmpty() && !Util.isTelPhoneNumber(mobileNumber) -> showMessage("手机号格式有误")
            else -> {
                val body = AddDrippingParam(
                    orgId = mOrgId,
                    raceId = mRaceId,
                    name = "",
                    contactName = name,
                    contactMobile = mobileNumber,
                    address = address,
                    lon = mLongitude,
                    lat = mLatitude,
                    pigeons = mList
                )
                showLoading(getString(R.string.loading))
                mViewModel.addOrderDidi(body)
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 滴滴接鸽-创建订单（会员角色） */
        mViewModel.addDrippingResult.observe(this) {
            val intent = Intent()
            intent.putExtra("isRefresh", true)
            finish(intent)
        }
        /** 获取用户所属公棚下会员列表 */
        mViewModel.loftMemberResult.observe(this) { it ->
            loftMemberResult.clear()
            if (!it.isEmpty()) {
                loftMemberResult.addAll(it.list)
                if (loftMemberResult.size == 1) {
                    if (::dialog.isInitialized) {
                        dialog.setMemberName(loftMemberResult[0].name)
                    }
                    mMemberId = loftMemberResult[0].id
                } else {
                    showMemberDialog()
                }
                it.list.forEach {
                    if (mMemberId == it.id) {
                        if (::dialog.isInitialized)
                            dialog.setMemberName(it.name)
                    }
                }
            }
        }
        /** 获取羽色 */
        mViewModel.featherColorResult.observe(this) {
            if (it.isSuccess) {
                pigeonFeatherColor(it.listData)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }
    }

    private fun showMemberDialog() {
        val rxDialog = RxMemberListDialog(this)
        rxDialog.setData(loftMemberResult)
        rxDialog.setOnMemberNameClickListener(object : RxMemberListDialog.OnMemberNameClickListener {
            override fun onItemClick(position: Int, name: String, id: Int) {
                dialog.setMemberName(name)
                mMemberId = loftMemberResult[0].id
                rxDialog.dismiss()
            }
        })
        rxDialog.setFullScreenWidth()
        rxDialog.show()
    }

    private fun pigeonFeatherColor(listData: ArrayList<FeatherColorResponse.ColorList>?) {
        val flyKey: ArrayList<String> = arrayListOf()
        if (listData != null && listData.size != 0) {
            listData.forEachIndexed { _, colorList ->
                flyKey.add(colorList.featherColor)
            }
        }

        val picker = OptionPicker(this, flyKey)
        picker.setCanceledOnTouchOutside(false)
        picker.setDividerRatio(WheelView.DividerConfig.FILL)
        picker.setShadowColor(Color.rgb(9, 155, 251), 40)
        picker.selectedIndex = mPositionColor
        picker.setCycleDisable(true)
        picker.setTitleText("请选择羽色")
        picker.setTitleTextColor(Color.BLACK)
        picker.setTitleTextSize(18)
        picker.setSubmitText("确认")
        picker.setSubmitTextSize(17)
        picker.setSubmitTextColor(Color.rgb(9, 155, 251))//确定按钮文字颜色
        picker.setCancelText("取消")
        picker.setCancelTextSize(17)
        picker.setCancelTextColor(Color.rgb(9, 155, 251))//取消按钮文字颜色
        picker.setTextSize(18)
        picker.setLineSpaceMultiplier(3.0F)
        picker.setOnOptionPickListener(object : OptionPicker.OnOptionPickListener() {
            override fun onOptionPicked(index: Int, item: String) {
                colorId = listData?.get(index)!!.id
                if (::dialog.isInitialized)
                    dialog.setFeatherColor(item)
                mPositionColor = index
            }
        })
        val window: Window = picker.window
        val lp: WindowManager.LayoutParams = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        picker.setWidth(WindowManager.LayoutParams.MATCH_PARENT)
        picker.show()
    }

    private fun showDialogAddPigeon() {
        dialog = RxDialogAddPigeon(this)
        dialog.setFeatherColorListener {
            mViewModel.getFeatherColor()
        }
        dialog.setMemberListener {
            mViewModel.getLoftMemberListByUserIdAndOrgId(mOrgId.toString(), mRaceId)
        }
        dialog.setCommitListener {
            addPigeon(dialog)
        }
        dialog.setFullScreenWidth()
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

    private fun addPigeon(dialog: RxDialogAddPigeon) {
        val list: ArrayList<AddDrippingParam.PigeonInfoBean> = arrayListOf()
        val ringId = dialog.getRingId()
        val ringIdYear = dialog.getRingIdYear()
        val ringIdArea = dialog.getRingIdArea()
        val pigeonName = dialog.getPigeonName()
        val pigeonSex = dialog.getPigeonSex()
        val pigeonEyePattern = dialog.getEyePattern()
        val pigeonDes = dialog.getPigeonDescribe()

        when {
            mMemberId == 0 -> RxToast.warning("选择会员")
            ringId.isEmpty() || ringIdYear.isEmpty() || ringIdArea.isEmpty() -> RxToast.warning("未完善足环号")
            pigeonSex == 0 -> RxToast.warning("选择赛鸽性别")
            colorId == 0 -> RxToast.warning("选择羽色")
            pigeonEyePattern == 0 -> RxToast.warning("选择眼沙")
            else -> {
                val pigeonRingId = "$ringIdYear-$ringIdArea-$ringId"
                val param = AddDrippingParam.PigeonInfoBean(
                    ringId = pigeonRingId,
                    ringSn = "",
                    name = pigeonName,
                    sex = pigeonSex,
                    sexStr = dialog.getPigeonSexStr(),
                    featherColor = colorId,
                    featherColorStr = dialog.getFeatherColorStr(),
                    eyePattern = pigeonEyePattern,
                    eyePatternStr = dialog.getPigeonEyePatternStr(),
                    pigeonDesc = pigeonDes,
                    memberId = mMemberId
                )
                mList.add(param)
                list.add(param)
                mAdapter.addData(mList.size - 1, list)
                /** 通知适配器新元素添加 */
                mAdapter.notifyItemInserted(mList.size)
                dialog.dismiss()
            }
        }
    }

}